<template>
  <div class="discovery">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>设备发现</span>
          <el-button 
            v-if="!discovering"
            type="primary" 
            @click="startDiscovery"
          >
            开始发现
          </el-button>
          <el-button 
            v-else
            type="danger" 
            @click="stopDiscovery"
          >
            停止发现
          </el-button>
        </div>
      </template>
      
      <div class="discovery-progress" v-if="discovering">
        <el-progress :percentage="discoveryProgress" :status="discoveryStatus" />
        <p class="progress-text">{{ discoveryStatusText }}</p>
      </div>
      
      <div class="discovered-devices">
        <h3>发现的设备 ({{ discoveredDevices.length }})</h3>
        
        <!-- 默认认证信息配置 -->
        <el-card class="auth-config-card" v-if="discoveredDevices.length > 0" shadow="never">
          <template #header>
            <div class="auth-config-header">
              <span>默认ONVIF认证信息</span>
              <el-tooltip content="批量添加设备时将使用这些默认的用户名和密码" placement="top">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <div class="auth-config-content">
            <el-form :model="defaultAuth" inline size="small">
              <el-form-item label="用户名">
                <el-input 
                  v-model="defaultAuth.username" 
                  placeholder="默认用户名"
                  style="width: 120px"
                  clearable
                />
              </el-form-item>
              <el-form-item label="密码">
                <el-input 
                  v-model="defaultAuth.password" 
                  type="password" 
                  placeholder="默认密码"
                  style="width: 120px"
                  show-password
                  clearable
                />
              </el-form-item>
              <el-form-item>
                <el-button 
                  size="small" 
                  @click="resetDefaultAuth"
                  :disabled="!defaultAuth.username && !defaultAuth.password"
                >
                  重置
                </el-button>
              </el-form-item>
              <el-form-item>
                <el-button 
                  size="small" 
                  type="primary" 
                  @click="saveDefaultAuth"
                >
                  保存配置
                </el-button>
              </el-form-item>
            </el-form>
            
            <!-- 预设配置管理 -->
            <div class="auth-presets">
              <div class="preset-header">
                <span class="preset-label">常用配置：</span>
                <el-button 
                  size="small" 
                  type="primary" 
                  plain
                  @click="showAddPresetDialog"
                  :icon="Plus"
                >
                  新增预设
                </el-button>
              </div>
              <div class="preset-list">
                <div 
                  v-for="(preset, index) in authPresets" 
                  :key="index"
                  class="preset-item"
                >
                  <el-button 
                    size="small" 
                    plain 
                    @click="setPresetAuth(preset.username, preset.password)"
                    class="preset-button"
                  >
                    {{ preset.username }}/{{ preset.password || '空密码' }}
                  </el-button>
                  <div class="preset-actions">
                    <el-button 
                      size="small" 
                      type="primary" 
                      text
                      @click="editPreset(index)"
                      :icon="Edit"
                    />
                    <el-button 
                      size="small" 
                      type="danger" 
                      text
                      @click="deletePreset(index)"
                      :icon="Delete"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 预设配置编辑对话框 -->
        <el-dialog 
          v-model="presetDialogVisible" 
          :title="isEditingPreset ? '编辑预设配置' : '新增预设配置'"
          width="400px"
        >
          <el-form :model="presetForm" label-width="80px">
            <el-form-item label="用户名" required>
              <el-input 
                v-model="presetForm.username" 
                placeholder="请输入用户名"
                clearable
              />
            </el-form-item>
            <el-form-item label="密码">
              <el-input 
                v-model="presetForm.password" 
                type="password"
                placeholder="请输入密码（可为空）"
                show-password
                clearable
              />
            </el-form-item>
            <el-form-item label="描述">
              <el-input 
                v-model="presetForm.description" 
                placeholder="可选的描述信息"
                clearable
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="presetDialogVisible = false">取消</el-button>
              <el-button 
                type="primary" 
                @click="savePreset"
                :disabled="!presetForm.username"
              >
                {{ isEditingPreset ? '保存' : '添加' }}
              </el-button>
            </div>
          </template>
        </el-dialog>

        <el-table 
          ref="deviceTable"
          :data="discoveredDevices" 
          v-loading="discovering" 
          stripe
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="name" label="设备名称" width="200" />
          <el-table-column prop="ipAddress" label="IP地址" width="150" />
          <el-table-column prop="manufacturer" label="厂商" width="120" />
          <el-table-column prop="model" label="型号" width="150" />
          <el-table-column prop="deviceType" label="设备类型" width="120" />
          <el-table-column prop="onvifPort" label="ONVIF端口" width="100" />
          <el-table-column prop="location" label="位置" width="120" />
          <el-table-column prop="discoveryTime" label="发现时间" width="180" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button size="small" @click="testConnection(row)" :loading="row.testing">
                测试连接
              </el-button>
              <el-button 
                size="small" 
                type="primary" 
                @click="addDevice(row)" 
                :disabled="row.status !== '在线'"
                :loading="row.adding"
              >
                {{ row.adding ? '添加中...' : '添加设备' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="batch-actions" v-if="discoveredDevices.length > 0">
          <div class="batch-info">
            <span v-if="selectedDevices.length > 0" class="selected-count">
              已选择 {{ selectedDevices.length }} 个设备
            </span>
          </div>
          <div class="batch-buttons">
            <el-button @click="selectAll" :disabled="discoveredDevices.length === 0">
              全选
            </el-button>
            <el-button @click="clearSelection" :disabled="selectedDevices.length === 0">
              清空选择
            </el-button>
            <el-button 
              type="primary" 
              @click="batchAdd" 
              :disabled="selectedDevices.length === 0 || batchOperationInProgress"
              :loading="batchOperationInProgress"
            >
              {{ batchOperationInProgress ? '批量添加中...' : `批量添加 (${selectedDevices.length})` }}
            </el-button>
            <el-button @click="exportResults" :disabled="discoveredDevices.length === 0">
              导出结果
            </el-button>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import { ElMessage, ElNotification, ElMessageBox } from 'element-plus'
import { QuestionFilled, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { discoverDevices, addDiscoveredDevice, batchAddDevices } from '@/api/discovery'
import { useDeviceStore } from '@/stores/device'

const router = useRouter()
const deviceStore = useDeviceStore()
const discovering = ref(false)
const discoveryProgress = ref(0)
const discoveryStatus = ref('')
const discoveryStatusText = ref('')

// 发现的设备列表
const discoveredDevices = ref([])

// 批量操作相关
const selectedDevices = ref([])
const batchOperationInProgress = ref(false)

// 默认认证信息
const defaultAuth = ref({
  username: 'admin',
  password: 'admin'
})

// 从本地存储加载默认认证信息和预设配置
const loadDefaultAuth = () => {
  // 加载默认认证信息
  const savedAuth = localStorage.getItem('onvif-default-auth')
  if (savedAuth) {
    try {
      const parsed = JSON.parse(savedAuth)
      defaultAuth.value = { ...defaultAuth.value, ...parsed }
    } catch (e) {
      console.warn('Failed to parse saved auth config:', e)
    }
  }
  
  // 加载预设配置
  const savedPresets = localStorage.getItem('onvif-auth-presets')
  if (savedPresets) {
    try {
      const parsed = JSON.parse(savedPresets)
      authPresets.value = parsed
    } catch (e) {
      console.warn('Failed to parse saved presets:', e)
    }
  }
}

// 保存默认认证信息到本地存储
const saveDefaultAuth = () => {
  localStorage.setItem('onvif-default-auth', JSON.stringify(defaultAuth.value))
  ElMessage.success('默认认证信息已保存')
}

// 保存预设配置到本地存储
const savePresetsToStorage = () => {
  localStorage.setItem('onvif-auth-presets', JSON.stringify(authPresets.value))
}

// 重置默认认证信息
const resetDefaultAuth = () => {
  defaultAuth.value = {
    username: 'admin',
    password: 'admin'
  }
  ElMessage.info('已重置为默认配置')
}

// 设置预设认证信息
const setPresetAuth = (username, password) => {
  defaultAuth.value.username = username
  defaultAuth.value.password = password
  ElMessage.success(`已设置为 ${username}/${password || '空密码'}`)
}

// 显示新增预设对话框
const showAddPresetDialog = () => {
  isEditingPreset.value = false
  editingPresetIndex.value = -1
  presetForm.value = {
    username: '',
    password: '',
    description: ''
  }
  presetDialogVisible.value = true
}

// 编辑预设配置
const editPreset = (index) => {
  isEditingPreset.value = true
  editingPresetIndex.value = index
  const preset = authPresets.value[index]
  presetForm.value = {
    username: preset.username,
    password: preset.password,
    description: preset.description || ''
  }
  presetDialogVisible.value = true
}

// 删除预设配置
const deletePreset = async (index) => {
  const preset = authPresets.value[index]
  try {
    await ElMessageBox.confirm(
      `确定要删除预设配置 "${preset.username}/${preset.password || '空密码'}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    authPresets.value.splice(index, 1)
    savePresetsToStorage()
    ElMessage.success('预设配置已删除')
  } catch (error) {
    // 用户取消删除
  }
}

// 保存预设配置
const savePreset = () => {
  if (!presetForm.value.username.trim()) {
    ElMessage.warning('请输入用户名')
    return
  }
  
  // 检查是否重复（编辑时排除自己）
  const isDuplicate = authPresets.value.some((preset, index) => {
    if (isEditingPreset.value && index === editingPresetIndex.value) {
      return false
    }
    return preset.username === presetForm.value.username && 
           preset.password === presetForm.value.password
  })
  
  if (isDuplicate) {
    ElMessage.warning('该用户名和密码组合已存在')
    return
  }
  
  const newPreset = {
    username: presetForm.value.username.trim(),
    password: presetForm.value.password,
    description: presetForm.value.description.trim() || ''
  }
  
  if (isEditingPreset.value) {
    // 编辑现有预设
    authPresets.value[editingPresetIndex.value] = newPreset
    ElMessage.success('预设配置已更新')
  } else {
    // 添加新预设
    authPresets.value.push(newPreset)
    ElMessage.success('预设配置已添加')
  }
  
  savePresetsToStorage()
  presetDialogVisible.value = false
}

// 页面加载时初始化默认认证信息
loadDefaultAuth()

// 处理设备数据
// 数据处理辅助函数 - 简化版本
const processDeviceData = (device) => {
  console.log('=== 开始处理设备数据 ===', device)
  
  // 直接使用设备对象的所有字段，不做复杂映射
  const processedDevice = {
    id: device.id || `${device.ipAddress || device.ip}_${Date.now()}`,
    name: device.name || device.deviceName || `设备-${device.ipAddress || device.ip}`,
    ipAddress: device.ipAddress || device.ip || '未知IP',
    manufacturer: device.manufacturer || '未知厂商',
    model: device.model || '未知型号', 
    deviceType: device.deviceType || device.type || 'Camera',
    onvifPort: device.onvifPort || device.port || 80,
    location: device.location || '未知位置',
    discoveryTime: device.discoveryTime || new Date().toLocaleString(),
    status: '在线',
    testing: false,
    serialNumber: device.serialNumber || '',
    firmwareVersion: device.firmwareVersion || '',
    hardwareId: device.hardwareId || '',
    rawData: device
  }
  
  console.log('=== 处理后的设备数据 ===', processedDevice)
  return processedDevice
}

// 开始设备发现 - 简化版本
const startDiscovery = async () => {
  console.log('=== 开始设备发现 ===')
  discovering.value = true
  discoveryProgress.value = 0
  discoveredDevices.value = []
  
  try {
    discoveryStatusText.value = '正在搜索ONVIF设备...'
    discoveryProgress.value = 30
    
    const response = await discoverDevices()
    console.log('=== API完整响应 ===', response)
    console.log('=== response.data ===', response.data)
    console.log('=== response.data类型 ===', typeof response.data)
    
    discoveryProgress.value = 80
    
    let devices = []
    // 直接判断response是否为数组
    if (Array.isArray(response)) {
      devices = response
      console.log('=== 直接从response提取设备 ===', devices)
    } else if (response && Array.isArray(response.data)) {
      devices = response.data
      console.log('=== 从response.data提取设备 ===', devices)
    } else if (response && response.data && Array.isArray(response.data.data)) {
      devices = response.data.data
      console.log('=== 从response.data.data提取设备 ===', devices)
    } else {
      // 简化的数据提取逻辑
      if (response && response.data) {
        // 直接检查data字段是否为数组
        if (Array.isArray(response.data.data)) {
          devices = response.data.data
          console.log('=== 从response.data.data提取设备 ===', devices)
        } else if (Array.isArray(response.data)) {
          devices = response.data  
          console.log('=== 从response.data提取设备 ===', devices)
        } else {
          console.log('=== 未找到设备数组，尝试查找所有数组字段 ===')
          console.log('=== response.data的所有键 ===', Object.keys(response.data))
          
          // 查找任何数组字段
          for (const [key, value] of Object.entries(response.data)) {
            console.log(`=== 检查字段 ${key} ===`, typeof value, Array.isArray(value))
            if (Array.isArray(value) && value.length > 0) {
              console.log(`=== 找到数组字段 ${key}，内容 ===`, value)
              devices = value
              break
            }
          }
        }
      }
    }
    
    console.log('=== 最终提取的设备数组 ===', devices)
    console.log('=== 设备数量 ===', devices.length)
    
    if (devices && devices.length > 0) {
      console.log('=== 开始处理设备数据 ===')
      
      // 处理每个设备
      const processedDevices = devices.map((device, index) => {
        console.log(`=== 处理第${index + 1}个设备 ===`, device)
        return processDeviceData(device)
      })
      
      console.log('=== 所有设备处理完成 ===', processedDevices)
      
      // 强制更新响应式数据
      discoveredDevices.value = [...processedDevices]
      
      console.log('=== discoveredDevices.value更新后 ===', discoveredDevices.value)
      console.log('=== discoveredDevices.value长度 ===', discoveredDevices.value.length)
      
      // 强制触发页面更新
      nextTick(() => {
        console.log('=== nextTick后的discoveredDevices ===', discoveredDevices.value)
      })
      
      discoveryProgress.value = 100
      discoveryStatus.value = 'success'
      discoveryStatusText.value = `发现完成，找到 ${processedDevices.length} 个设备`
      ElMessage.success(`发现完成，找到 ${processedDevices.length} 个设备`)
    } else {
      console.log('=== 未找到任何设备 ===')
      discoveryProgress.value = 100
      discoveryStatus.value = 'success' 
      discoveryStatusText.value = '发现完成，未找到设备'
      ElMessage.info('未发现任何设备')
    }
  } catch (error) {
    console.error('=== 设备发现失败 ===', error)
    discoveryProgress.value = 100
    discoveryStatus.value = 'exception'
    discoveryStatusText.value = '设备发现失败'
    ElMessage.error(`设备发现失败: ${error.message}`)
  } finally {
    discovering.value = false
  }
}

// 停止发现
const stopDiscovery = () => {
  discovering.value = false
  discoveryStatus.value = 'stopped'
  discoveryStatusText.value = '发现已停止'
  ElMessage.info('设备发现已停止')
}

// 测试连接
const testConnection = async (device) => {
  device.testing = true
  
  try {
    // 模拟测试连接
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 根据设备类型判断连接状态
    let isOnline = true
    if (device.deviceType === 'Unknown') {
      isOnline = Math.random() > 0.5 // 未知设备随机结果
    } else if (device.deviceType === 'Camera') {
      isOnline = Math.random() > 0.2 // 摄像头设备大概率在线
    }
    
    if (isOnline) {
      device.status = '在线'
      ElMessage.success(`设备 ${device.ipAddress} 连接测试成功`)
    } else {
      device.status = '离线'
      ElMessage.warning(`设备 ${device.ipAddress} 连接测试失败`)
    }
  } catch (error) {
    console.error('连接测试失败:', error)
    device.status = '离线'
    ElMessage.error(`设备 ${device.ipAddress} 连接测试失败: ${error.message || '未知错误'}`)
  } finally {
    device.testing = false
  }
}

// 添加设备
const addDevice = async (device) => {
  device.adding = true
  try {
    // 构造符合后端期望的请求格式
    const requestData = {
      discoveredDevice: device.rawData,
      customName: device.name,
      description: `通过设备发现添加 - ${device.name}`,
      // 使用配置的默认认证信息
      username: defaultAuth.value.username || 'admin',
      password: defaultAuth.value.password || 'admin'
    }
    
    console.log('=== 发送添加设备请求 ===', requestData)
    
    // 调用添加设备API
    const res = await addDiscoveredDevice(requestData)
    
    console.log('=== 添加设备响应 ===', res)
    console.log('=== response.code ===', res.code)
    console.log('=== response.msg ===', res.msg)
    
    // 修复成功判断逻辑 - 根据不同的code码判断结果
    // 200: 全部成功, 206: 部分成功, 400: 全部失败, 500: 服务器错误
    const isSuccess = res && (res.code === 200 || res.code === 206)
    const isPartialSuccess = res && res.code === 206
    const isAllFailed = res && res.code === 400
    const result = res.data || res
    
    console.log('=== isSuccess ===', isSuccess)
    console.log('=== isPartialSuccess ===', isPartialSuccess)
    console.log('=== isAllFailed ===', isAllFailed)
    console.log('=== result ===', result)
    
    if (isSuccess) {
      // 使用后端返回的msg作为成功消息
      const successMsg = res.msg || `设备 "${device.name}" 已成功添加到设备管理列表！`
      
      ElMessage({
        message: successMsg,
        type: 'success',
        duration: 4000,
        showClose: true
      })
      
      // 显示通知，引导用户查看设备管理页面
      ElNotification({
        title: '设备添加成功',
        message: `${successMsg}。您可以在设备管理页面查看和管理该设备。`,
        type: 'success',
        duration: 6000,
        position: 'top-right',
        onClick: () => {
          // 点击通知跳转到设备管理页面
          router.push('/devices')
        }
      })
      
      // 添加成功后将该设备从发现列表移除
      discoveredDevices.value = discoveredDevices.value.filter(d => d.id !== device.id)
      
      // 刷新设备管理列表（如有全局store或事件总线可触发刷新）
      if (deviceStore && deviceStore.fetchDevices) {
        deviceStore.fetchDevices()
      }
    } else {
      const errorMsg = res && res.msg ? res.msg : (res && res.message ? res.message : '设备添加失败')
      console.error('=== 设备添加失败 ===', errorMsg, res)
      ElMessage.error(errorMsg)
    }
  } catch (e) {
    console.error('=== 添加设备异常 ===', e)
    ElMessage.error('添加设备异常: ' + (e.message || e))
  } finally {
    device.adding = false
  }
}

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedDevices.value = selection
  console.log('=== 选择的设备 ===', selectedDevices.value)
}

// 预设配置管理
const authPresets = ref([
  { username: 'admin', password: 'admin', description: '默认配置' },
  { username: 'admin', password: '123456', description: '常用密码' },
  { username: 'admin', password: '', description: '无密码' },
  { username: 'root', password: 'root', description: 'Root用户' }
])

// 预设配置对话框
const presetDialogVisible = ref(false)
const isEditingPreset = ref(false)
const editingPresetIndex = ref(-1)
const presetForm = ref({
  username: '',
  password: '',
  description: ''
})

// 添加表格引用
const deviceTable = ref(null)

// 全选功能
const selectAll = () => {
  if (deviceTable.value) {
    deviceTable.value.toggleAllSelection()
  }
}

// 清空选择
const clearSelection = () => {
  selectedDevices.value = []
  if (deviceTable.value) {
    deviceTable.value.clearSelection()
  }
}

// 批量添加设备
const batchAdd = async () => {
  if (selectedDevices.value.length === 0) {
    ElMessage.warning('请先选择要添加的设备')
    return
  }

  // 过滤出在线设备
  const onlineDevices = selectedDevices.value.filter(device => device.status === '在线')
  if (onlineDevices.length === 0) {
    ElMessage.warning('选中的设备中没有在线设备，无法添加')
    return
  }

  if (onlineDevices.length < selectedDevices.value.length) {
    const offlineCount = selectedDevices.value.length - onlineDevices.length
    const result = await ElMessageBox.confirm(
      `选中的设备中有 ${offlineCount} 个离线设备将被跳过，是否继续添加 ${onlineDevices.length} 个在线设备？`,
      '确认批量添加',
      {
        confirmButtonText: '继续添加',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).catch(() => false)
    
    if (!result) return
  } else {
    const result = await ElMessageBox.confirm(
      `确定要批量添加选中的 ${onlineDevices.length} 个设备吗？`,
      '确认批量添加',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    ).catch(() => false)
    
    if (!result) return
  }

  batchOperationInProgress.value = true

  try {
    // 构造批量添加请求数据
    const batchRequest = {
      devices: onlineDevices.map(device => ({
        ipAddress: device.ipAddress,
        port: device.onvifPort || 80,
        customName: device.name,
        description: `通过设备发现批量添加 - ${device.name}`,
        // 使用配置的默认认证信息
        username: defaultAuth.value.username || 'admin',
        password: defaultAuth.value.password || 'admin'
      })),
      ignoreConnectionFailures: true,
      timeoutSeconds: 30
    }

    console.log('=== 批量添加请求数据 ===', batchRequest)

    const response = await batchAddDevices(batchRequest)
     
     console.log('=== 批量添加响应 ===', response)
     console.log('=== response.code ===', response.code)
     console.log('=== response.data ===', response.data)

     // 修复成功判断逻辑 - 根据不同的code码判断结果
     // 200: 全部成功, 206: 部分成功, 400: 全部失败, 500: 服务器错误
     const isSuccess = response && (response.code === 200 || response.code === 206)
     const isPartialSuccess = response && response.code === 206
     const isAllFailed = response && response.code === 400
     const result = response.data || response
     
     console.log('=== isSuccess ===', isSuccess)
     console.log('=== isPartialSuccess ===', isPartialSuccess)
     console.log('=== isAllFailed ===', isAllFailed)
     console.log('=== result ===', result)

     if (isSuccess && result) {
       // 使用后端返回的msg作为主要消息，如果没有则使用默认格式
       const backendMsg = response.msg || ''
       const successCount = result.successCount || 0
       const failureCount = result.failureCount || 0
       
       console.log('=== successCount ===', successCount)
       console.log('=== failureCount ===', failureCount)
       console.log('=== backendMsg ===', backendMsg)
       
       let message = ''
       let messageType = 'success'
       
       if (backendMsg) {
         // 优先使用后端返回的消息
         message = backendMsg
         if (failureCount === 0) {
           messageType = 'success'
         } else if (successCount === 0) {
           messageType = 'error'
         } else {
           messageType = 'warning'
         }
       } else {
         // 后端没有返回消息时使用默认格式
         if (failureCount === 0) {
           message = `批量添加成功！共添加了 ${successCount} 个设备`
           messageType = 'success'
         } else if (successCount === 0) {
           message = `批量添加失败！${failureCount} 个设备添加失败`
           messageType = 'error'
         } else {
           message = `批量添加完成！成功添加 ${successCount} 个设备，${failureCount} 个设备添加失败`
           messageType = 'warning'
         }
       }
       
       // 显示消息
       if (messageType === 'success') {
         ElMessage.success(message)
       } else if (messageType === 'error') {
         ElMessage.error(message)
       } else {
         ElMessage.warning(message)
       }

       // 显示详细通知
       ElNotification({
         title: '批量添加结果',
         message: `${message}。您可以在设备管理页面查看添加的设备。`,
         type: messageType,
         duration: 8000,
         position: 'top-right',
         onClick: () => {
           router.push('/devices')
         }
       })

       // 移除成功添加的设备
       if (successCount > 0) {
         const successDevices = result.successDevices || []
         console.log('=== successDevices ===', successDevices)
         
         if (successDevices.length > 0) {
           const successIps = successDevices.map(device => device.ipAddress)
           discoveredDevices.value = discoveredDevices.value.filter(
             device => !successIps.includes(device.ipAddress)
           )
         } else {
           // 如果没有详细的成功设备列表，根据成功数量移除选中的设备
           const onlineDevices = selectedDevices.value.filter(device => device.status === '在线')
           const devicesToRemove = onlineDevices.slice(0, successCount)
           const ipsToRemove = devicesToRemove.map(device => device.ipAddress)
           discoveredDevices.value = discoveredDevices.value.filter(
             device => !ipsToRemove.includes(device.ipAddress)
           )
         }
         
         // 清空选择
         selectedDevices.value = []
         
         // 刷新设备管理列表
         if (deviceStore && deviceStore.fetchDevices) {
           deviceStore.fetchDevices()
         }
       }

       // 如果有失败的设备，显示失败详情
       if (failureCount > 0 && result.failedDevices && result.failedDevices.length > 0) {
         console.warn('=== 添加失败的设备 ===', result.failedDevices)
         
         // 构建失败设备的详细信息
         const failureDetails = result.failedDevices.map(failedDevice => 
           `${failedDevice.ipAddress}:${failedDevice.port} - ${failedDevice.errorMessage}`
         ).join('\n')
         
         // 显示失败设备的详细通知
         ElNotification({
           title: '部分设备添加失败',
           message: `以下设备添加失败：\n${failureDetails}`,
           type: 'warning',
           duration: 10000,
           position: 'top-right',
           dangerouslyUseHTMLString: false
         })
       }

     } else {
       const errorMsg = response && response.msg ? response.msg : (response && response.message ? response.message : '批量添加设备失败')
       console.error('=== 批量添加失败 ===', errorMsg, response)
       ElMessage.error(errorMsg)
     }

  } catch (error) {
    console.error('=== 批量添加异常 ===', error)
    ElMessage.error('批量添加设备异常: ' + (error.message || error))
  } finally {
    batchOperationInProgress.value = false
  }
}

const exportResults = () => {
  ElMessage.info('导出功能待实现')
}

// 状态类型
const getStatusType = (status) => {
  switch (status) {
    case '在线':
      return 'success'
    case '离线':
      return 'danger'
    case '未知':
      return 'warning'
    default:
      return 'info'
  }
}
</script>

<style scoped>
.discovery {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.discovery-progress {
  margin: 20px 0;
}

.progress-text {
  text-align: center;
  margin-top: 10px;
  color: var(--el-text-color-regular);
}

.discovered-devices h3 {
  margin-bottom: 15px;
}

.batch-actions {
  margin-top: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.auth-config-card {
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
}

.auth-config-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.auth-config-content {
  padding: 10px 0;
}

.auth-presets {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #f0f0f0;
}

.preset-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 15px;
}

.preset-label {
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.preset-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.preset-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.preset-button {
  flex: 1;
  margin: 0;
  justify-content: flex-start;
}

.preset-actions {
  display: flex;
  gap: 4px;
  margin-left: 12px;
}

.preset-actions .el-button {
  margin: 0;
  padding: 4px;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 8px;
}

.batch-info {
  margin-bottom: 10px;
}

.selected-count {
  color: var(--el-color-primary);
  font-weight: 500;
  font-size: 14px;
}

.batch-buttons {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.batch-buttons .el-button {
  margin: 0;
}

@media (max-width: 768px) {
  .batch-buttons {
    flex-direction: column;
    align-items: stretch;
  }
  
  .batch-buttons .el-button {
    width: 100%;
    margin-bottom: 8px;
  }
}

/* 表格样式优化 */
.el-table {
  margin-bottom: 20px;
}

.el-table .el-table__cell {
  padding: 8px 0;
}
</style>